package com.cn.jinl.service;


import com.cn.jinl.api.IBoxManageService;
import com.cn.jinl.api.IOrderOutInfoService;
import com.cn.jinl.api.IProductStorageOutService;
import com.cn.jinl.dao.*;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ProductStorageOutServiceImpl implements IProductStorageOutService {

    @Autowired
    private ProductStorageOutMapper productStorageOutMapper;

    @Autowired
    private ProductStorageOutRelateMapper productStorageOutRelateMapper;

    @Autowired
    private IOrderOutInfoService orderOutInfoService;

    @Autowired
    private BoxManageMapper boxManageMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderOutRelateMapper orderOutRelateMapper;

    @Autowired
    private GenerateUUID generateUUID;

    @Override
    public List<ProductStorageOutVo> getProductStorageOutList(QueryForm queryForm) throws Exception {
        int count = productStorageOutMapper.selectOrderStorageOutListCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductStorageOutVo> productStorageOut = productStorageOutMapper.selectOrderStorageOutList(queryForm);
        productStorageOut.get(0).setCount(count);
        return productStorageOut;
    }

    @Override
    public List<ProductStorageOutVo> getProductStorageOutListMX(QueryForm queryForm) throws Exception {
        //默认查询近三个月
        if (queryForm.getStartTime() == null || queryForm.getStartTime().isEmpty()) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            // 设置endTime为当前时间
            queryForm.setEndTime(sdf1.format(new Date()));
            // 设置startTime为3个月前
            calendar.add(Calendar.MONTH, -3);
            queryForm.setStartTime(sdf.format(calendar.getTime()));
        }
        int count = productStorageOutMapper.selectOrderStorageOutMXListCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductStorageOutVo> productStorageOut = productStorageOutMapper.selectOrderStorageOutMXList(queryForm);
        productStorageOut.get(0).setCount(count);
        return productStorageOut;
    }

    @Override
    public List<ProductStorageOrderVo> getProductStorageByOrderId(String orderId) throws Exception {
        if(StringUtils.isEmpty(orderId)){
            return Lists.newArrayList();
        }
        return productStorageOutMapper.selectProductStorageByOrderId(orderId);
    }

    @Override
    public List<ProductStorageOutRelate> getProductStorageOutRelateListByOrderId(String orderId) throws Exception {
        ProductStorageOutRelateExample example = new ProductStorageOutRelateExample();
        example.createCriteria().andRelateIdEqualTo(orderId);
        example.setOrderByClause("box_code asc");
        List<ProductStorageOutRelate> relates = productStorageOutRelateMapper.selectByExample(example);
        return relates;
    }

    @Override
    public Map<String, Integer> getProductStorageRelateCountMap(String storageOutId) throws Exception {
        if(StringUtils.isEmpty(storageOutId)){
            return Maps.newHashMap();
        }
        ProductStorageOutRelateExample example = new ProductStorageOutRelateExample();
        example.createCriteria().andStroageOutIdEqualTo(storageOutId);
        List<ProductStorageOutRelate> relates = productStorageOutRelateMapper.selectByExample(example);
        Map<String,Integer> map = Maps.newHashMap();
        for(ProductStorageOutRelate outRelate : relates){
            String relateId = outRelate.getRelateId();
            if(map.containsKey(relateId)){
                int count = map.get(relateId)+1;
                map.put(relateId,count);
            }else{
                map.put(relateId,1);
            }
        }
        return map;
    }

    @Override
    public String addProductStorageOut(ProductStorageOut productStorageOut) throws Exception {

        return null;
    }

    @Override
    public String addBatchProductStorageOut(List<OrderOutInfo> orderOutInfos) throws Exception {
        if(CollectionUtils.isEmpty(orderOutInfos)){
            return "参数列表为空！";
        }
        List<ProductStorageOut> outs = Lists.newArrayList();
        for(OrderOutInfo orderOutInfo : orderOutInfos){
            String id = orderOutInfo.getId();
            ProductStorageOut out = new ProductStorageOut();
            out.setRelateId(id);
            out.setStorageOutType("1");
            out.setId(CommonUtil.generateRandomNum("porductout-"));
            outs.add(out);
        }
        int count = productStorageOutMapper.batchInsertStorageOuts(outs);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateProductStorageOut(ProductStorageOut productStorageOut) throws Exception {
        return null;
    }


    @Override
    public String addBatchProductStorageRelates(StorageOutVo storageOutVo) throws Exception {
        if(StringUtils.isEmpty(storageOutVo.getId())){
            return "参数为空！";
        }
        if(CollectionUtils.isEmpty(storageOutVo.getStorages())){
            return "请扫码出库！";
        }
        OrderOutInfo orderOutInfo = orderOutInfoService.getOrderOutInfoById(storageOutVo.getId());
        if(null == orderOutInfo || StringUtils.isEmpty(orderOutInfo.getId())){
            return "VoidTime！";
        }
        ProductStorageOutExample example = new ProductStorageOutExample();
        example.createCriteria().andRelateIdEqualTo(storageOutVo.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductStorageOut> outs = productStorageOutMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(outs)){
            return "未查询到出库任务！";
        }
        if(outs.size() != 1){
            return "出库任务不为一";
        }

        ProductStorageOut productStorageOut = outs.get(0);
        if(!StringUtils.equals(productStorageOut.getStorageOutStatus(),"0")){
            return "货物已出库！";
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String outTime = simpleDateFormat.format(new Date());
        OrderOutInfo update  = new OrderOutInfo();
        update.setId(orderOutInfo.getId());
        update.setOutStorageTime(outTime);
        update.setOutStorageUser(storageOutVo.getUserName());
        update.setOrderOutStatus("1");
        String resp = orderOutInfoService.updateOrderOutInfo(update);
        if(!StringUtils.isEmpty(resp)){
            return resp;
        }
        List<BoxManage> boxManages = Lists.newArrayList();
        List<ProductStorageOutRelate> relates = storageOutVo.getStorages();
        int boxCodeCount = 0;
        List<Order> updateOrderSendGoods = Lists.newArrayList();
        Map<String,Integer> orderMap = Maps.newHashMap();
        for(ProductStorageOutRelate relate : relates){
            relate.setStroageOutId(productStorageOut.getId());
            if(StringUtils.isNotEmpty(relate.getBoxCode())){
                BoxManage boxManage = new BoxManage();
                boxManage.setBoxCode(relate.getBoxCode());
                boxManage.setPrintCode("1");
                boxManage.setCodeStatus("6");
                boxManages.add(boxManage);
            }
            ++boxCodeCount;
            if(orderMap.containsKey(relate.getRelateId())){
                int count = orderMap.get(relate.getRelateId())+1;
                orderMap.put(relate.getRelateId(),count);
            }else{
                orderMap.put(relate.getRelateId(),1);
            }
        }
        List<String> orderIds = orderOutRelateMapper.selectOrderIdsByOutId(orderOutInfo.getId());
        for(String oid:orderIds){
            Order order = new Order();
            order.setId(oid);
            int goods = 0;
            if(orderMap.containsKey(oid)){
                goods = orderMap.get(oid);
            }
            order.setSendGoodsCount(goods+"");
            order.setGoodsStatus("1");
            order.setOrderStatus("8");
            updateOrderSendGoods.add(order);
        }

        int count  = productStorageOutRelateMapper.batchInsertOutRelates(relates);
        if(count < 1){
            throw new Exception("更新出库副表异常！");
        }
        if(updateOrderSendGoods.size() > 0){
            count = orderMapper.batchUpdateOrderGoodsStatus(updateOrderSendGoods);
            if(count < 1){
                throw new Exception("更新订单表异常！");
            }
        }

        if(!CollectionUtils.isEmpty(boxManages)){
            count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
            if(count < 1){
                throw new Exception("更新箱码表异常！");
            }
        }

        String key = "CK"+generateUUID.getYearMoth();
        int num = generateUUID.getNumberFlag(key);
        String code = key+generateUUID.getTwoNumStr(num);
        ProductStorageOut updateOut = new ProductStorageOut();
        updateOut.setId(productStorageOut.getId());
        updateOut.setStorageOutStatus("1");
        updateOut.setStorageOutCount(boxCodeCount+"");
        updateOut.setStorageOutTime(outTime);
        updateOut.setStorageOutUser(storageOutVo.getUserName());
        updateOut.setStorageOutCode(code);
        count = productStorageOutMapper.updateByExampleSelective(updateOut,example);
        if(count < 1){
            throw new Exception("更新出库表异常！");
        }
        return CommonUtil.outStr(count);
    }

    //测试平库出库
    @Override
    public String addBatchProductStorageRelates1(StorageOutVo storageOutVo) throws Exception {
        if(StringUtils.isEmpty(storageOutVo.getId())){
            return "参数为空！";
        }
        if(CollectionUtils.isEmpty(storageOutVo.getStorages())){
            return "请扫码出库！";
        }
        OrderOutInfo orderOutInfo = orderOutInfoService.getOrderOutInfoById(storageOutVo.getId());
        if(null == orderOutInfo || StringUtils.isEmpty(orderOutInfo.getId())){
            return "发货任务不存在！";
        }
        ProductStorageOutExample example = new ProductStorageOutExample();
        example.createCriteria().andRelateIdEqualTo(storageOutVo.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductStorageOut> outs = productStorageOutMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(outs)){
            return "未查询到出库任务！";
        }
        ProductStorageOut productStorageOut = outs.get(0);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String outTime = simpleDateFormat.format(new Date());
        OrderOutInfo update  = new OrderOutInfo();
        update.setId(orderOutInfo.getId());
        update.setOutStorageTime(outTime);
        update.setOutStorageUser(storageOutVo.getUserName());
        update.setOrderOutStatus("1");
        String resp = orderOutInfoService.updateOrderOutInfo(update);
        if(!StringUtils.isEmpty(resp)){
            return resp;
        }
        List<BoxManage> boxManages = Lists.newArrayList();
        List<ProductStorageOutRelate> relates = storageOutVo.getStorages();
        int boxCodeCount = 0;
        List<Order> updateOrderSendGoods = Lists.newArrayList();
        Map<String,Integer> orderMap = Maps.newHashMap();
        for(ProductStorageOutRelate relate : relates){
            relate.setStroageOutId(productStorageOut.getId());
            //清理出库没有订单跟任务所以设置为1写死
            relate.setRelateId("1");
            if(StringUtils.isNotEmpty(relate.getBoxCode())){
                BoxManage boxManage = new BoxManage();
                boxManage.setBoxCode(relate.getBoxCode());
                boxManage.setPrintCode("1");
                boxManage.setCodeStatus("7");
                boxManages.add(boxManage);
            }
            ++boxCodeCount;
            if(orderMap.containsKey(relate.getRelateId())){
                int count = orderMap.get(relate.getRelateId())+1;
                orderMap.put(relate.getRelateId(),count);
            }else{
                orderMap.put(relate.getRelateId(),1);
            }
        }
        List<String> orderIds = orderOutRelateMapper.selectOrderIdsByOutId(orderOutInfo.getId());
        for(String oid:orderIds){
            Order order = new Order();
            order.setId(oid);
            int goods = 0;
            if(orderMap.containsKey(oid)){
                goods = orderMap.get(oid);
            }
            order.setSendGoodsCount(goods+"");
            order.setGoodsStatus("1");
            order.setOrderStatus("8");
            updateOrderSendGoods.add(order);
        }

        int count  = productStorageOutRelateMapper.batchInsertOutRelates(relates);
        if(count < 1){
            throw new Exception("更新出库副表异常！");
        }
        if(updateOrderSendGoods.size() > 0){
            count = orderMapper.batchUpdateOrderGoodsStatus(updateOrderSendGoods);
            if(count < 1){
                throw new Exception("更新订单表异常！");
            }
        }

        if(!CollectionUtils.isEmpty(boxManages)){
            count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
            if(count < 1){
                throw new Exception("更新箱码表异常！");
            }
        }

        String key = "CK"+generateUUID.getYearMoth();
        int num = generateUUID.getNumberFlag(key);
        String code = key+generateUUID.getTwoNumStr(num);
        ProductStorageOut updateOut = new ProductStorageOut();
        updateOut.setId(productStorageOut.getId());
        updateOut.setStorageOutStatus("1");
        updateOut.setStorageOutType("2");
        updateOut.setStorageOutCount(boxCodeCount+"");
        updateOut.setStorageOutTime(outTime);
        updateOut.setStorageOutUser(storageOutVo.getUserName());
        updateOut.setStorageOutCode(code);
        count = productStorageOutMapper.updateByExampleSelective(updateOut,example);
        if(count < 1){
            throw new Exception("更新出库表异常！");
        }
        return CommonUtil.outStr(count);
    }


    @Override
    public int getProductOutingStorage() throws Exception {
        ProductStorageOutExample example = new ProductStorageOutExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andStorageOutStatusEqualTo("0");
        return productStorageOutMapper.countByExample(example);
    }

    @Override
    public String cancel(QueryForm queryForm) throws Exception {
        List<String> ids = queryForm.getIds();
        if (CollectionsUtil.isEmpty(ids)){
            return "请选中要作废的数据！";
        }
        //TODO 设备表可能关联其他表，判断是否可以删除

        ProductStorageOut productStorageOut = new ProductStorageOut();
        productStorageOut.setStorageOutStatus(Constants.DEL_STATUS);
        ProductStorageOutExample example = new ProductStorageOutExample();
        example.createCriteria().andIdIn(ids);
        int count = productStorageOutMapper.updateByExampleSelective(productStorageOut,example);

        return CommonUtil.outStr(count);
    }
}
